import paramiko
import time
import os
import socket
import sys
socket.setdefaulttimeout(240)

logins = ["wanemen", "crookeshanks", "pekuar", "seriph89", "ethkan", 'aleicht', 'infernus58', 'alfric', 'varos0', 'shadowthorn29', 'seriph', 'vinuh', 'nudgestone', 'zindlestone', 'knacknell', 'nordobo']

host = "ssh.alwaysdata.com"
user = "wanemen"
password = "haslo1234"


class InstallAgent(object):
    def __init__(self, host, user, passowrd):
        self.host = host
        self.user = user
        self.password = password
    
    def install_spade(self, path):
        '''
        path - path to tar.gz file with spade
        '''
        ssh = paramiko.SSHClient()
        #ssh.load_system_host_keys()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.host, username = self.user, password = self.password)
        ftp = ssh.open_sftp()
        stdin, stdout, stderr = ssh.exec_command("rm spade.tar.gz; rm spade2-read-only2/ -rf")
        ftp.put(path, "spade.tar.gz")
        ssh.exec_command("tar xvfz spade.tar.gz")
        time.sleep(5)
        stdin, stdout, stderr = ssh.exec_command("cd ./spade2-read-only2; python setup.py build")
        print "".join( stdout.readlines() )
        print "".join( stderr.readlines() )
        stdin, stdout, stderr = ssh.exec_command("rm spade.tar.gz; cd ./spade2-read-only2; rm etc -rf; rm s* -rf; rm t* -rf; rm x* -rf; rm c* -rf; rm u* -rf; rm C* -rf; rm r* -rf")
        time.sleep(5)
        ssh.exec_command("mkdir libs; cd spade*/build/lib*/; mv * ../../../libs")
        ssh.exec_command("rm spade* -rf")
        ssh.close()

        
    def install_agents(self, path):
        '''
        path - path to folder with agents
        '''
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.host, username = self.user, password = self.password)
        ftp = ssh.open_sftp()
        for i,j,k in os.walk(path):
            for f in k:
                ftp.put( os.path.join(path, f) , "./libs/" + f)
            break
        ssh.close()

    
    def run_agent(self, name, host, LB_type, cons_hash = '1'):
        '''
        LB_type
	        1 - SenderLB
	        2 - RandomLB
	        3 - CentralizedLB
        '''
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.host, username = self.user, password = self.password)
        #stdin, stdout, stderr = ssh.exec_command("cd libs; screen -dmS 1234 python CrawlerAgent.py %s %s" % (name, host) )
        stdin, stdout, stderr = ssh.exec_command("cd libs; screen -dmS 1234 python main.py %s %s %s %s" % (name, host, LB_type, cons_hash) )
        print "".join( stdout.readlines() )
        print "".join( stderr.readlines() )
        ssh.close()

        
    def kill_agent(self):
        ssh = paramiko.SSHClient()
        ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy())
        ssh.connect(self.host, username = self.user, password = self.password)
        #stdin, stdout, stderr = ssh.exec_command("cd libs; screen -dmS 1234 python CrawlerAgent.py %s %s" % (name, host) )
        stdin, stdout, stderr = ssh.exec_command( "killall screen" )
        print "".join( stdout.readlines() )
        print "".join( stderr.readlines() )
        ssh.close()
        
        

if __name__ == "__main__":
    agents = []
    for login in logins:
      try:   
        print login
        i_agent = InstallAgent(host, login, password)
        i_agent.install_spade("/home/adam/Studia/VIII semestr/SIA/projekt/program/spade.tar.gz")
        i_agent.install_agents("/home/adam/Studia/VIII semestr/SIA/projekt/program/agenci/sia-crawling/")
        agents.append(i_agent)
      except paramiko.AuthenticationException, e:
        print e
    sys.exit(0)
    """
    for i, agent in enumerate(agents):
      while True:
        print i
        try:
          agent.kill_agent()
        except socket.error, e:
          pass
        else:
          break
    sys.exit(0)
    """
    for i, agent in enumerate(agents):
      while True:
        print i
        try:
          agent.run_agent("agent" + str(i), "89.79.246.138", "1", "1")
        except socket.error, e:
          pass
        else:
          break
    
    
